<!-- 商品属性页面 -->
<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, UploadProps } from 'element-plus'

//当前显示的页数
let currentPage = ref(1)

//分页器一页里面显示几个
let pageSize = ref(3)

// 总共的页数
let totalPage = ref(0)

//渲染的商品信息
let goodsData = ref([])

// 控制对话框的显示隐藏
let dialogFormVisible = ref(false)

// form表单组件实例
const formRef = ref()

// 收集新增的品牌数据
let trademarkParams = reactive({
  tmName: '',
  logoUrl: '',
})

// 自定义校验表单和图片函数
const validatorTmName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('品牌名称位数要大于等于两位'))
  }
}

const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  if (value) {
    callBack()
  } else {
    callBack(new Error('请上传图片！'))
  }
}
//表单校验规则
const formRule = {
  tmName: [
    {
      required: true,
      // message: '品牌名不能为空',
      trigger: 'blur',
      validator: validatorTmName,
    },
  ],
  logoUrl: [
    {
      required: true,
      // message: '品牌照片不能为空',
      trigger: 'blur',
      validator: validatorLogoUrl,
    },
  ],
}
//获取后端的商品数据
const getTradeInfo = async (pager = 1) => {
  currentPage.value = pager
  let res = await reqHasTrademark(currentPage.value, pageSize.value)
  if (res.code === 200) {
    //后端商品数据的传来
    goodsData.value = res.data.records
    totalPage.value = res.data.total
  }
  // console.log(res)
}

//添加/修改/删除品牌的一系列事件
const addProduct = () => {
  dialogFormVisible.value = true
  //清空数据
  trademarkParams.id = 0
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
  // 清空校验的错误信息
  nextTick(() => {
    formRef.value.clearValidate('logoUrl')
    formRef.value.clearValidate('tmName')
  })
}
const editProduct = (row: any) => {
  dialogFormVisible.value = true
  //展示编辑的数据
  // trademarkParams.id = row.id
  // trademarkParams.tmName = row.tmName
  // trademarkParams.logoUrl = row.logoUrl
  // console.log('editROw', row)

  Object.assign(trademarkParams, row) //使用新语法合并
  // 在渲染之后清除校验的提示
  nextTick(() => {
    formRef.value.clearValidate('logoUrl')
    formRef.value.clearValidate('tmName')
  })
}
const deleteProduct = async (id: number) => {
  // console.log('deleteId', id)
  let res = await reqDeleteTrademark(id)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getTradeInfo(
      goodsData.value.length > 1 ? currentPage.value : currentPage.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
  getTradeInfo()
  // console.log('delete')
}

// 对话框的确定和取消
const confirm = async () => {
  //统一表单校验
  await formRef.value.validate()
  // console.log(checkres)

  let res: any = await reqAddOrUpdateTrademark(trademarkParams)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改新品牌成功' : '添加新品牌成功',
    })
    getTradeInfo(trademarkParams.id ? currentPage.value : 1)
  } else {
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改新品牌失败' : '添加新品牌失败',
    })
  }
  dialogFormVisible.value = false
}
const cancel = () => {
  dialogFormVisible.value = false
}

//图片上传之前
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any) => {
  if (
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小小于4M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件格式务必PNG|JPG|GIF',
    })
    return false
  }
}
//图片成功上传
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  // console.log('相应', response)
  trademarkParams.logoUrl = response.data
  // 清除表单校验的错误提示
  formRef.value.clearValidate('logoUrl')
}

onMounted(() => {
  getTradeInfo()
})
</script>

<template>
  <el-card class="box-card">
    <!-- <div v-for="o in 4" :key="o" class="text item">{{ 'List item ' + o }}</div> -->
    <el-button type="primary" icon="Plus" @click="addProduct">
      添加品牌
    </el-button>
    <!-- 表格 -->
    <el-table style="margin: 10px 0px" border :data="goodsData">
      <el-table-column
        label="序号"
        width="80px"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌LOGO">
        <template #="{ row, $index }">
          <img :src="row.logoUrl" alt="" style="height: 100px; width: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="editProduct(row)"
          ></el-button>
          <el-popconfirm
            :title="`你确定要删除${row.tmName}品牌？`"
            width="250px"
            icon="Delete"
            @confirm="deleteProduct(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="getTradeInfo"
      @size-change="getTradeInfo"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[1, 2, 3, 4]"
      :background="true"
      layout="prev, pager, next, jumper,-> ,total, sizes,"
      :total="totalPage"
    />
  </el-card>
  <!-- 弹出的对话框 -->
  <el-dialog
    v-model="dialogFormVisible"
    :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
  >
    <!-- 收集的数据框 -->
    <el-form :model="trademarkParams" :rules="formRule" ref="formRef">
      <el-form-item label="品牌名称" label-width="90px" prop="tmName">
        <el-input
          placeholder="请输入内容"
          v-model="trademarkParams.tmName"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌Logo" label-width="90px" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="trademarkParams.logoUrl"
            :src="trademarkParams.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <!-- 按钮 -->
    <template #footer>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>

      <el-button type="primary" size="default" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
